package Thread.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}21:49
 */
public class ABADemo {
    static AtomicReference<Integer> atomicReference = new AtomicReference<>(100);

    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100,1);

    public static void main(String[] args) {
        new Thread(() ->{
            atomicReference.compareAndSet(100,101);
            atomicReference.compareAndSet(101,100);
        },"t1").start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(atomicReference.compareAndSet(100,2019)+"\t"+atomicReference.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t2").start();

        new Thread(() -> {
            int stampe = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName()+": "+stampe);

            //保证
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(atomicReference.compareAndSet(100,2019)+"\t"+atomicReference.get());
                atomicStampedReference.compareAndSet(100,101,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t3").start();


        new Thread(() -> {
            int stampe = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName()+": "+stampe);

            //保证
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(atomicReference.compareAndSet(100,2019)+"\t"+atomicReference.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t4").start();
    }
}
